// ignore_for_file: file_names, must_be_immutable, constant_identifier_names, slash_for_doc_comments, avoid_unnecessary_containers, prefer_const_constructors, unnecessary_cast, sized_box_for_whitespace, prefer_function_declarations_over_variables, overridden_fields, annotate_overrides, prefer_const_literals_to_create_immutables, unnecessary_null_comparison, deprecated_member_use, invalid_use_of_protected_member, unused_element, unused_local_variable, avoid_print

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mybase/base/abstract/IFFRefresh.dart';
import 'package:mybase/base/abstract/IFFScaffold.dart';
import 'package:mybase/base/config/FFireBaseManager.dart';
import 'package:mybase/base/tool/Animated/AnimatedSkeleton.dart';
import 'package:mybase/base/tool/color/FFColor.dart';
import 'package:mybase/base/tool/empty/FFEmpty.dart';
import 'package:mybase/base/widget/layout/FFMoreBrach.dart';

/**页面父类，所有的页面都应该继承此类 */
class FFScaffold extends StatefulWidget {
  String? ffName;

  FFScaffold({Key? key, this.ffName}) : super(key: key);

  @override
  State<FFScaffold> createState() => FFScaffoldState();
}

class FFScaffoldState extends State<FFScaffold>
    with
        RouteAware,
        // SingleTickerProviderStateMixin, //单个AnimationController
        TickerProviderStateMixin, //有多个AnimationController
        AutomaticKeepAliveClientMixin,
        WidgetsBindingObserver {
  List<dynamic> datas = [];

  /**页面基础控制 */
  late IFFScaffold iffScaffold;

  /**刷新控制 */
  IFFRefresh? iffRefresh;

  /**这次的状态与上次的状态是否改变了 */
  bool _statusChanged = false;

  /**上一次的状态 */
  FFPageStatus _lastPageStatus = FFPageStatus.firstLoading;

  @override
  void initState() {
    /**子类初始化方法 */
    WidgetsBinding.instance.addObserver(this);
    _printPageName();
    iffScaffold.ffInitState();
    ffInitStateAfterLoadData();
    FFireBaseManager().goPageBefore(widget.toString());
    super.initState();
  }

  /**找印页面名字，方便查找*/
  _printPageName() {
    String? pageInfo = ffPageInfo();
    if (!FFEmpty.stringIsEmpty(pageInfo)) {
      debugPrint("""
    
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
         进入到页面：class ${widget.toString()}
         该页面说明：
            ${pageInfo ?? "----"}
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    """);
    } else {
      debugPrint("""
    
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
         进入到页面：class ${widget.toString()}
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    """);
    }
  }

  /**用来说明该页面作用*/
  String? ffPageInfo() {
    return null;
  }

  void ffInitStateAfterLoadData() {
    if (iffRefresh != null) {
      iffRefresh!.ffFirstRefresh = true;
      iffRefresh!.ffRefresh(true);
    }
  }

  /**每个页面都可以自定义主题*/
  Widget ffBuildTheme(BuildContext context, {required Widget child}) {
    return Theme(
        data: ThemeData(
          primarySwatch: FFColor.createMaterialColor(
              Color.fromRGBO(56, 204, 96, 1.0).withAlpha(100)),
        ),
        child: child);
  }

  /**多语言渲染*/
  ffLanguageBuild(BuildContext context) {}

  /**刷新父类,子类使用自己的setState也是一样的*/
  ffSuperSetState() {
    setState(() {});
  }

  bool isAndroidAndIOS() {
    return (Platform.isAndroid || Platform.isIOS) ? true : false;
  }

  @override
  Widget build(BuildContext context) {
    ffLanguageBuild(context);
    if (wantKeepAlive == true) super.build(context);
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value:
          iffScaffold.ffStyle?.ffStatusTextColor ?? SystemUiOverlayStyle.dark,
      child: MediaQuery.removePadding(
        context: context,
        removeTop: iffScaffold.ffTabbarRemoveTop ?? false,
        child: ffBuildTheme(context, child: _scaffold(context)),
      ),
    );
  }

  Widget _scaffold(BuildContext context) {
    return GestureDetector(
      onTap: () {
        // 收起键盘
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: WillPopScope(
        onWillPop: ffOnWillPop,
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          floatingActionButton: iffScaffold.ffloatingActionButton(context),
          backgroundColor:
              iffScaffold.ffStyle?.ffStatusBackgroundColor ?? Colors.white,
          bottomNavigationBar: iffScaffold.ffBottomNavigationBar(context),
          body: Column(
            children: [
              ///导航栏
              //MediaQuery.removePadding 很重要
              MediaQuery.removePadding(
                context: context,
                child: iffScaffold.ffNavi(context) ?? Container(),
                removeBottom: true,
              ),

              ///导航栏 底部固定区域
              iffScaffold.ffNaviBottomFixedArea(context) ?? Container(),

              Expanded(
                child: FFMoreBrach(
                  condition: iffScaffold.ffPageStatus,
                  builderWidget: (BuildContext ctx, dynamic condition) {
                    //状态过渡有动画
                    Widget? thisWidget;
                    if (condition is FFPageStatus) {
                      if (_lastPageStatus != condition) {
                        _statusChanged = !_statusChanged;
                      }

                      if (condition == FFPageStatus.firstLoading) {
                        thisWidget = iffScaffold.ffFirstLoadingWidget(context);
                      } else if (condition == FFPageStatus.noData) {
                        thisWidget = _refreshWidget(
                            context,
                            iffScaffold.ffNoDataWidget(context,
                                    obj: FFEventObj(firstRefresh: () {
                                  ffRequestFirstRefresh();
                                })) ??
                                Container(),
                            condition);
                      } else if (condition == FFPageStatus.netError) {
                        thisWidget = _refreshWidget(
                            context,
                            iffScaffold.ffNetErrorWidget(context,
                                    obj: FFEventObj(firstRefresh: () {
                                  ffRequestFirstRefresh();
                                })) ??
                                Container(),
                            condition);
                      } else if (condition == FFPageStatus.result) {
                        thisWidget = _refreshWidget(
                            context,
                            iffScaffold.ffBody(context) ?? Container(),
                            condition);
                      }

                      _lastPageStatus = condition;
                    }

                    return Container(
                      width: MediaQuery.of(context).size.width,
                      color: iffScaffold.ffStyle?.ffBodyColor ?? Colors.white,
                      child: AnimatedSkeleton(
                        isLoading: _statusChanged,
                        skeletonWidget: thisWidget ?? Container(),
                        body: Container(
                          child: thisWidget,
                        ),
                      ),
                    );
                  },
                ),
              ),

              ///底部固定
              iffScaffold.ffBottom(context) ?? Container(),
              Container(
                padding: iffScaffold.ffPageSpacingParam?.bottomSpacing == true
                    ? EdgeInsets.only(
                        bottom: MediaQuery.of(context).padding.bottom * 0.55)
                    : null,
              )
            ],
          ),
        ),
      ),
    );
  }

  ///重新进入第一次刷新
  void ffRequestFirstRefresh() {
    iffScaffold.ffPageStatus = FFPageStatus.firstLoading;
    setState(() {});
    ffRequestBackRefresh();
  }

  ///后台偷偷刷新，正常情况下不显示加载效果
  void ffRequestBackRefresh() {
    if (iffRefresh?.ffrefreshApiStatus != RefreshApiStatus.status_none) {
      print("正在刷新，忽略");
      return;
    }
    if (iffScaffold.ffPageStatus == FFPageStatus.noData ||
        iffScaffold.ffPageStatus == FFPageStatus.netError) {
      iffScaffold.ffPageStatus = FFPageStatus.firstLoading;
      setState(() {});
    }
    iffRefresh?.ffRefresh(true);
  }

  ///能否侧滑返回
  Future<bool> ffOnWillPop() {
    return Future(() => true);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (ModalRoute.of(context) is PageRoute) {
      routeObserver.subscribe(this, ModalRoute.of(context) as PageRoute);
    }
    FFireBaseManager().getGlobal()?.ffDidChangeDependencies(this,context);
    iffScaffold.ffDidChangeDependencies();
  }

  ///键盘高度变化
  ffKeyBoardChange(EdgeInsets insets) {}

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    WidgetsBinding.instance.addPostFrameCallback((time) {
      ffKeyBoardChange(MediaQuery.of(context).viewInsets);
    });
  }

  /**页面销毁执行些方法 */
  @override
  void dispose() {
    print("页面销毁...");
    routeObserver.unsubscribe(this);
    iffScaffold.ffDispose();
    WidgetsBinding.instance.removeObserver(this);
    FFireBaseManager().getGlobal()?.ffRemoveObserver(this);
    super.dispose();
  }

  /**push到当前页面 */
  @override
  void didPush() {
    super.didPush();
  }

  /**当前页面push到下一页面 */
  @override
  void didPushNext() {
    super.didPushNext();
  }

  /**这个页面回到上个页面 */
  @override
  void didPop() {
    super.didPop();
  }

  /**回到这个页面 */
  @override
  void didPopNext() {
    super.didPopNext();
  }

  // @override
  // void didChangeAppLifecycleState(AppLifecycleState state) {
  //   super.didChangeAppLifecycleState(state);
  // }

  /**在tabbar切换过程中，当前页面是否保存*/
  @override
  bool get wantKeepAlive => false;
}

/**刷新管理 */
extension RefreshManager on FFScaffoldState {
  Widget _refreshWidget(BuildContext ctx, Widget child, FFPageStatus status) {
    if (iffRefresh != null) {
      return iffRefresh!.ffWidget(ctx, child, status);
    }
    return child;
  }
}
